package pers.cz.netty.protocal;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/**
 * @program: PostGirl-panent
 * @description: 消息加密
 * @author: Cheng Zhi
 * @create: 2022-10-04 15:31
 **/
public class MessageEncoder extends MessageToByteEncoder<Message> {

    private static final Logger log = LoggerFactory.getLogger(MessageEncoder.class);

    /*
    +------------------------------------------------------------------------------------------+
    | 魔数 8byte 使用String描述   |     报文类型 1byte      | 数据长度 8byte   使用long描述      |
    +-------------------------------------------------------------------------------------------+
    |                   数据内容 （长度不定）                                                    |
    +-------------------------------------------------------------------------------------------+
    |                   分割标识 8byte                                                          |
    +-------------------------------------------------------------------------------------------+
    */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {

        byteBuf.writeBytes(ProtocalConst.POCKET_MAGIC_NUM.getBytes());
        byteBuf.writeByte(message.getMsgType().type());
        // 消息长度和数据内容
        final Object content = message.getContent();
        if (content == null) {
            byteBuf.writeLong(0L);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(content);
            byte[] bytes = bos.toByteArray();
            byteBuf.writeLong(bytes.length);
            byteBuf.writeBytes(bytes);
        }
        //String splitSymbol = message.getSplitSymbol();
        //byteBuf.writeBytes(splitSymbol.getBytes());
    }
}
